package stack.be.touch.db;

import stack.be.touch.dto.SiteDTO;
import stack.be.touch.utils.Const;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.util.Log;

public class DatabaseHelper extends SQLiteOpenHelper {
	public static final String DATABASE_NAME = "stackexchange";
	private static final String TABLE_NAME = "sites";
	private static final int DATABASE_VERSION = 11;
	public static final String KEY_BOOKMARKED = "bookmarked";
	
//	public static final String KEY_ENDPOINT = BaseColumns._ID;
//	public static final String KEY_NAME = "name";
//	public static final String KEY_UID = "uid";
//	public static final String KEY_REPUTATION = "reputation";
//	public static final String KEY_POS = "position";
//	public static final String KEY_CHECKED = "checked";
//	public static final String KEY_UNAME = "user_name";
	
	private final Context context;
	
	public static DatabaseHelper getInstance(Context context, String databaseName) {
        return new DatabaseHelper(context, databaseName);
    }
	
	// TODO Chuyen Key_endpoint thanh unique
	private static final String SITES_TABLE_CREATE =
			"CREATE TABLE " + TABLE_NAME + "(" +
			SiteDTO.KEY_ENDPOINT + " TEXT PRIMARY KEY, " +
			SiteDTO.KEY_NAME + " TEXT, " +
			SiteDTO.KEY_UID + " NUMERIC, " +
			SiteDTO.KEY_REPUTATION + " INTEGER, " +
			SiteDTO.KEY_POS + " INTEGER, " +
			SiteDTO.KEY_CHECKED + " BOOLEAN, " +
			SiteDTO.KEY_UNAME + " TEXT)";
		
		public DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
			this.context = context;
		}
		
		public DatabaseHelper(Context context, String databaseName) {
	        super(context, databaseName, null, DATABASE_VERSION);
	        this.context = context;
	    }

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL(SITES_TABLE_CREATE);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			switch(oldVersion) {
			case 8:
				db.delete(TABLE_NAME, KEY_BOOKMARKED + " = ?", new String[] { "0" });
			case 9:
				db.execSQL("ALTER TABLE " + TABLE_NAME + " ADD COLUMN " + SiteDTO.KEY_REPUTATION + " INTEGER");
				break;
			case 10:
				try {
					db.execSQL("ALTER TABLE " + TABLE_NAME + " ADD COLUMN " + SiteDTO.KEY_REPUTATION + " INTEGER");
				}
				catch (Exception e) {
					// this is a bugfix
					Log.e(Const.TAG, "bugfix!");
				}
				break;
			default:
				db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
				onCreate(db);
				break;
			}
		}
	
	
}
